package org.pz.mq.demo;

import lombok.extern.slf4j.Slf4j;
import org.pz.entity.UserEntity;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
@Slf4j
public class MqDemoProductor {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 直连交换机
     * 交换机分发信息到所有能匹配到 routingKey 的队列
     * */
    public void directSendMsg(String msg) {
        log.info("生产者发送消息到交换机：{}, routingKey：{}，消息内容：{}", MqDemoConfig.direct_exchange, MqDemoConfig.direct_routeKey, msg);
        rabbitTemplate.convertAndSend(MqDemoConfig.direct_exchange, MqDemoConfig.direct_routeKey, msg);
    }

    /**
     * 扇形交换机
     * 所有与交换机匹配的队列都能收到消息
     * */
    public void fanoutSendMsg(String msg) {
        log.info("生产者发送消息到交换机：{}，消息内容：{}", MqDemoConfig.fanout_exchange, msg);
        rabbitTemplate.convertAndSend(MqDemoConfig.fanout_exchange, null, msg);
    }

    /**
     * 序列化
     * 消息体是一个实现序列化接口的实现类，消费者入参直接是这个实体类型的参数
     * */
    public void sendMsg(UserEntity user) {
        rabbitTemplate.convertAndSend(MqDemoConfig.direct_exchange, MqDemoConfig.direct_routeKey1, user);
    }

    /**
     * 触发发布确认的,交换机不存在的问题
     * */
    public void sendConfirmMsg(String msg) {
        // 生成唯一消息ID
        String messageId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(messageId);
        rabbitTemplate.convertAndSend("notExistsExchange", "notExistsRoutingKey", msg, correlationData);
    }

    /**
     * 触发消息回退的，交换机正常，分发队列异常
     * */
    public void sendReturnMsg(String msg) {
        String messageId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(messageId);
        rabbitTemplate.convertAndSend(MqDemoConfig.direct_exchange, "notExistsRoutingKey", msg, correlationData);
    }

    /**
     * 触发重试机制的生产者
     * */
    public void sendRetryMsg(String msg){
        String messageId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(messageId);
        rabbitTemplate.convertAndSend(MqDemoConfig.retry_exchange, MqDemoConfig.retry_routeKey, msg, correlationData);
    }

    /**
     * 死信队列
     * */
    public void sendDeadMsg(String msg){
        String messageId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(messageId);
        rabbitTemplate.convertAndSend(MqDemoConfig.dead_exchange, MqDemoConfig.dead_routeKey, msg, correlationData);
    }
}
